#include <WebsocketServer.h>

WebSocketServer::WebSocketServer(net::io_context &ioc, const unsigned short port)
    : _ioc(ioc), _acceptor(ioc, net::ip::tcp::endpoint(net::ip::tcp::v4(), port)) {
    std::clog << "Server start on port : " << port << std::endl;
    StartAccept();
}

void WebSocketServer::StartAccept() {
    auto &ioc = IOServicePool::GetInstance().GetIOContext();

    auto con_ptr = std::make_shared<Connection>(ioc);

    _acceptor.async_accept(con_ptr->GetSocket(), [this, con_ptr](const error_code &err) {
        try {
            if (!err) {
                std::clog << "建立TCP连接,对端 = " << con_ptr->GetUuid() << std::endl;
                con_ptr->AsyncAccept();
            }
            else {
                std::cerr << "acceptor async_accept failed, err is " << err.message() << std::endl;
            }

            StartAccept();
        }
        catch (std::exception &exp) {
            std::cout << "async_accept error is " << exp.what() << std::endl;
        }
    });
}
